﻿/**
 * Weighter
 * 
 * @author		Allen Chou
 * @version		1.0.0 (last update: Jan 26 2009)
 * @link        http://cjcat.blogspot.com
 * @link		http://cjcat2266.deviantart.com
 */

package idv.cjcat.utils {
	import flash.errors.IllegalOperationError;
	
	public class Weighter {
		
		public var values:Array;
		public var weights:Array;
		public var normalized:Boolean;
		
		public function Weighter(initValues:Array = null, initWeights:Array = null, normalized:Boolean = true) {
			if (initValues == null) values = new Array();
			else values = initValues;
			
			if (initWeights == null) weights = new Array();
			else weights = initWeights;
			
			this.normalized = normalized;
		}
		
		private var _value:Number;
		private var _normal:Number;
		public function valueOf():Number {
			if (values.length != weights.length) throw new IllegalOperationError("The lengths of the value array and the weight vector are not equal.");
			_value = _normal = 0;
			for (var i:int = 0; i < values.length; i++) {
				_value += values[i] * weights[i];
				_normal += weights[i];
			}
			if (normalized) {
				if (_normal != 0) return _value / _normal;
				else return NaN;
			} else {
				return _value;
			}
		}
		
		public function toString():String { return valueOf().toString(); }
	}
}